package cn.chanel.mall.controller;

import cn.chanel.mall.constant.CookieName;
import cn.chanel.mall.service.CategoryService;
import cn.chanel.mall.service.GoodsService;
import cn.chanel.mall.service.UserService;
import cn.chanel.mall.vo.GoodsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private GoodsService goodsService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private UserService userService;

    @GetMapping(path = "/{category}")
    public ModelAndView categoryGoods(@PathVariable String category,
                                      @RequestParam(required = false, defaultValue = "") String key,
                                      @CookieValue(name = CookieName.USER_LOGIN, required = false) String userId,
                                      Map<String, Object> map){
        List<GoodsVO> allGoods = goodsService.getAllGoodsByCategoryAndKey(category, key);
        map.put("allGoods", allGoods);
        map.put("allCategories", categoryService.getAllCategory());
        map.put("currentCategory", categoryService.getCategoryById(category));
        if(StringUtils.hasText(userId)){
            map.put("userInfo", userService.findUserById(userId));
        }
        return new ModelAndView("index", map);
    }

    @GetMapping(path = "/single")
    public ModelAndView getOneGoods(@RequestParam(required = false, defaultValue = "") String id,
                                      @CookieValue(name = CookieName.USER_LOGIN, required = false) String userId,
                                      Map<String, Object> map){
        if(StringUtils.hasText(userId)){
            map.put("userInfo", userService.findUserById(userId));
        }
        if(StringUtils.hasText(id)){
            GoodsVO goodsVO = goodsService.getGoodsById(id);
            map.put("goods", goodsVO);
        }
        return new ModelAndView("goods", map);
    }
}
